package com.lunatic.shiro.config;


import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import com.lunatic.shiro.realm.AccountRealm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;

@Configuration
public class ShiroConfig {

    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager) {
        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();
        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        HashMap<String, String> map = new HashMap<>();
        map.put("/main", "user");
        map.put("/manage", "perms[manage]");
        map.put("/administrator", "roles[admin]");

        // 设置未登录跳转页面
        shiroFilterFactoryBean.setLoginUrl("/login");
        // 设置未授权跳转页面
        shiroFilterFactoryBean.setUnauthorizedUrl("/unauthorized");

        shiroFilterFactoryBean.setFilterChainDefinitionMap(map);
        return shiroFilterFactoryBean;
    }


    /**
     * @return
     * @Qualifier 通过名字注入实例
     */
    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("accountRealm") AccountRealm accountRealm) {
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();
        defaultWebSecurityManager.setRealm(accountRealm);
        return defaultWebSecurityManager;
    }

    @Bean
    public AccountRealm accountRealm() {
        return new AccountRealm();
    }


    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }


}
